package com.sun.client;

import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.Hashtable;

import net.sf.ezmorph.bean.MorphDynaBean;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.imagine.step1.client.ImageListener;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sun.common.CommonMetaData;

public class SendNewVersionToClient extends IoHandlerAdapter{

	static final Logger logger = LoggerFactory.getLogger(SendNewVersionToClient.class);
	
	public static final int CONNECT_TIMEOUT = 60;

    private String host;
    private int port;
    private SocketConnector connector;
    private IoSession session;

    public SendNewVersionToClient(String host, int port, ImageListener imageListener,ProtocolCodecFactory factory) {
        this.host = host;
        this.port = port;
        connector = new NioSocketConnector();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
        connector.setHandler(this);
    }
    
    public void sentData() throws InterruptedException{
    	for (;;) {
	        try {
	            ConnectFuture future = connector.connect(new InetSocketAddress(host, port));
	            
	            future.awaitUninterruptibly();
	            
	            session = future.getSession();
	            
//	            ConfigRequestBean bean = new ConfigRequestBean();
//	        	
//	        	bean.setSysID("9999");
//	        	bean.setCurrentVersion("xxx");
//	        	session.write(bean);
	            break;
	        } catch (RuntimeIoException e) {
	        	
	            System.err.println("Failed to connect.");
	            
	            e.printStackTrace();
	            
	            Thread.sleep(5000);
	            
	        }
	    }
		
		session.getCloseFuture().awaitUninterruptibly();
		
	    connector.dispose();
    	
    }
    
    @Override
    public void sessionOpened(IoSession session) throws Exception {
    	
    	Hashtable<String, String> param= new Hashtable<String, String>();
    	
    	param.put(CommonMetaData.PROJECT_ID, "1");
    	
    	session.write(param);
    	
    }
    
    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
    	
    }
    
    @Override
    public void messageReceived(IoSession session, Object message)
    		throws Exception {
    	Hashtable<String, MorphDynaBean> beanHashtable = (Hashtable<String, MorphDynaBean>)message;
    	
    	Enumeration enumeration=beanHashtable.elements();
    	while(enumeration.hasMoreElements()){
    		System.out.println(BeanUtils.describe(enumeration.nextElement()));
    		
    	}
    	super.messageReceived(session, message);
    	session.close(true);
    }
    
    public static void main(String[] args) throws InterruptedException {
    	
    	ApplicationContext factory=new  ClassPathXmlApplicationContext("classpath:spring/Spring-Client-Config.xml");
    	SendNewVersionToClient client = new SendNewVersionToClient("localhost", 1921, null,(ProtocolCodecFactory) factory.getBean("clientCodeXFacory"));
    	client.sentData();
	}
}
